﻿using SIMS.Shared.Models;
using SIMS.SqlSugarWebApi.Models;
using SIMS.SqlSugarWebApi.ServiceInterface;
using SqlSugar;

namespace SIMS.SqlSugarWebApi.Services
{
    public class UserService : BaseService<User>, IUserService
    {
        private DataContext _context;

        public UserService(DataContext context) : base(context)
        {
            _context = context;
        }

        public PagingModel<UserRole> GetUserRoles(int? userId)
        {
            if (userId != null)
            {
                var userRoles = _context.db.Queryable<UserRole>().Where(x => x.UserId == userId);
                return new PagingModel<UserRole>()
                {
                    Count = userRoles.Count(),
                    Items = userRoles.ToList()
                };
            }
            else
            {
                return null;
            }
        }

        public async Task<PagingModel<User>> GetUsers(string userName, int pageNum, int pageSize)
        {
            ISugarQueryable<User> users;
            if (!string.IsNullOrEmpty(userName))
            {
                users = _context.db.Queryable<User>().Where(r => r.UserName.Contains(userName)).OrderBy(r => r.Id);
            }
            else
            {
                users = _context.db.Queryable<User>().OrderBy(r => r.Id);
            }
            int count = await users.CountAsync();
            List<User> items;
            if (pageSize > 0)
            {
                items = await users.ToPageListAsync(pageNum, pageSize);
            }
            else
            {
                items = await users.ToListAsync();
            }
            return new PagingModel<User>()
            {
                Count = count,
                Items = items
            };
        }

        public async Task<int> SetUserRoles(int userId, string roleIds)
        {
            string[] roles = roleIds.Split(',');
            if (roles.Length == 0)
            {
                return -1;//权限为空
            }
            if (userId < 1)
            {
                return -1;
            }
            await _context.db.Deleteable<UserRole>().Where(r => r.UserId == userId).ExecuteCommandAsync();
            
            var entities = roles.Select(r => new UserRole()
            {
                UserId = userId,
                RoleId = int.Parse(r)
            }).ToList();

            return await _context.db.Insertable(entities).ExecuteCommandAsync();
        }

    }
}
